<?php

namespace app\admin\controller\scanwork;

use app\common\controller\Backend;
use think\Db;
use Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 订单管理
 *
 * @icon fa fa-shopping-cart
 * @remark 管理工厂生产订单信息
 */
class Order extends Backend
{
    /**
     * Order模型对象
     * @var \app\admin\model\scanwork\Order
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\scanwork\Order;
        $this->view->assign("statusList", $this->model->getStatusList());
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with(['orderModels.model.product'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        // 获取产品型号列表
        $modelList = [];
        $models = \app\admin\model\scanwork\ProductModel::with('product')->select();
        foreach ($models as $model) {
            $displayName = $model->product->name . ' - ' . $model->name;
            if ($model->model_code) {
                $displayName .= ' (' . $model->model_code . ')';
            }
            $modelList[$model->id] = $displayName;
        }
        $this->view->assign('modelList', $modelList);
        
        // 加载自定义字段
        $customFieldsHtml = \app\admin\library\CustomFieldHelper::renderFields('order');
        $this->view->assign('customFieldsHtml', $customFieldsHtml);
        
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $modelData = $this->request->post("models");
            $customFields = $this->request->post("custom_fields/a");
            
            // 添加调试信息
            error_log("添加订单 - 接收到的数据:");
            error_log("params: " . json_encode($params));
            error_log("modelData: " . json_encode($modelData));
            
            // 处理JSON格式的型号数据
            if (is_string($modelData)) {
                $modelData = json_decode($modelData, true);
                error_log("解析后的modelData: " . json_encode($modelData));
            }
            
            if ($params && $modelData) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                
                // 生成订单号
                $params['order_no'] = $this->generateOrderNo();
                
                // 处理交货时间
                error_log("添加订单 - 交货时间原始值: " . json_encode($params['delivery_time']));
                if (!empty($params['delivery_time'])) {
                    $params['delivery_time'] = strtotime($params['delivery_time']);
                    error_log("添加订单 - 交货时间转换后: " . $params['delivery_time']);
                }
                
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    
                    // 保存订单
                    $result = $this->model->allowField(true)->save($params);
                    
                    // 保存订单型号
                    $totalQuantity = 0;
                    foreach ($modelData as $modelItem) {
                        if (isset($modelItem['model_id']) && isset($modelItem['quantity']) && $modelItem['quantity'] > 0) {
                            \app\admin\model\scanwork\OrderModel::create([
                                'order_id' => $this->model->id,
                                'model_id' => $modelItem['model_id'],
                                'quantity' => $modelItem['quantity']
                            ]);
                            $totalQuantity += $modelItem['quantity'];
                        }
                    }
                    
                    // 更新订单总数量
                    $this->model->save(['total_quantity' => $totalQuantity]);
                    
                    // 保存自定义字段
                    if ($customFields) {
                        \app\admin\library\CustomFieldHelper::saveFieldValues('order', $this->model->id, $customFields);
                    }
                    
                    // 自动计算物料需求
                    $this->calculateMaterialsWithCost($this->model->id);
                    
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            } else {
                $this->error(__('Parameter %s can not be empty', ''));
            }
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->find($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        
        // 获取产品型号列表
        $modelList = [];
        $models = \app\admin\model\scanwork\ProductModel::with('product')->select();
        foreach ($models as $model) {
            $displayName = $model->product->name . ' - ' . $model->name;
            if ($model->model_code) {
                $displayName .= ' (' . $model->model_code . ')';
            }
            $modelList[$model->id] = $displayName;
        }
        $this->view->assign('modelList', $modelList);
        
        // 获取订单型号数据
        $orderModels = \app\admin\model\scanwork\OrderModel::where('order_id', $ids)->select();
        $this->view->assign('orderModels', $orderModels);
        
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $modelData = $this->request->post("models");
            
            // 添加调试信息
            error_log("编辑订单 - 接收到的数据:");
            error_log("params: " . json_encode($params));
            error_log("modelData: " . json_encode($modelData));
            
            // 处理JSON格式的型号数据
            if (is_string($modelData)) {
                $modelData = json_decode($modelData, true);
                error_log("解析后的modelData: " . json_encode($modelData));
            }
            
            if ($params && $modelData) {
                $params = $this->preExcludeFields($params);
                
                // 处理交货时间
                error_log("编辑订单 - 交货时间原始值: " . json_encode($params['delivery_time']));
                if (!empty($params['delivery_time'])) {
                    $params['delivery_time'] = strtotime($params['delivery_time']);
                    error_log("编辑订单 - 交货时间转换后: " . $params['delivery_time']);
                }
                
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $name;
                        $row->validateFailException(true)->validate($validate);
                    }
                    
                    // 更新订单
                    $result = $row->allowField(true)->save($params);
                    
                    // 删除原有订单型号
                    \app\admin\model\scanwork\OrderModel::where('order_id', $ids)->delete();
                    
                    // 保存新的订单型号
                    $totalQuantity = 0;
                    foreach ($modelData as $modelItem) {
                        if (isset($modelItem['model_id']) && isset($modelItem['quantity']) && $modelItem['quantity'] > 0) {
                            \app\admin\model\scanwork\OrderModel::create([
                                'order_id' => $ids,
                                'model_id' => $modelItem['model_id'],
                                'quantity' => $modelItem['quantity']
                            ]);
                            $totalQuantity += $modelItem['quantity'];
                        }
                    }
                    
                    // 更新订单总数量
                    $row->save(['total_quantity' => $totalQuantity]);
                    
                    // 重新计算物料需求
                    \app\admin\model\scanwork\OrderMaterial::where('order_id', $ids)->delete();
                    $this->calculateMaterialsWithCost($ids);
                    
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            } else {
                $this->error(__('Parameter %s can not be empty', ''));
            }
        }
        // 添加调试信息
        error_log("编辑订单 - 订单数据: " . json_encode($row->toArray()));
        error_log("编辑订单 - delivery_time值: " . json_encode($row->delivery_time));
        
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $item) {
                    // 检查是否有关联的分工分配
                    $allocationCount = \app\admin\model\scanwork\Allocation::where('order_id', $item->id)->count();
                    if ($allocationCount > 0) {
                        throw new Exception("订单【{$item->order_no}】下还有{$allocationCount}个分工分配，请先删除相关分工");
                    }
                    
                    // 删除订单型号
                    \app\admin\model\scanwork\OrderModel::where('order_id', $item->id)->delete();
                    
                    $count += $item->delete();
                }
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        } else {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
    }

    /**
     * 查看详情
     */
    public function detail($ids = null)
    {
        $row = $this->model->find($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        
        // 获取订单型号详情
        $orderModels = \app\admin\model\scanwork\OrderModel::with(['model.product'])->where('order_id', $ids)->select();
        
        // 获取分工分配详情
        $allocations = \app\admin\model\scanwork\Allocation::with(['model.product', 'process', 'user'])
            ->where('order_id', $ids)
            ->select();
        
        $this->view->assign('row', $row);
        $this->view->assign('orderModels', $orderModels);
        $this->view->assign('allocations', $allocations);
        
        return $this->view->fetch();
    }

    /**
     * 生成订单号
     */
    private function generateOrderNo()
    {
        $prefix = 'ORD';
        $date = date('Ymd');
        $random = strtoupper(substr(md5(uniqid()), 0, 6));
        return $prefix . $date . $random;
    }

    /**
     * Excel导入订单
     */
    public function import()
    {
        if ($this->request->isPost()) {
            $file = $this->request->file('file');
            if (!$file) {
                $this->error('请选择文件');
            }
            
            $ext = pathinfo($file->getInfo('name'), PATHINFO_EXTENSION);
            if (!in_array($ext, ['xlsx', 'xls'])) {
                $this->error('文件格式错误，请上传Excel文件');
            }
            
            try {
                // 使用PhpSpreadsheet读取Excel
                $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file->getPathname());
                $worksheet = $spreadsheet->getActiveSheet();
                $data = $worksheet->toArray();
                
                // 过滤空行
                $validData = [];
                foreach ($data as $row) {
                    if (!empty(array_filter($row, function($cell) { return !is_null($cell) && $cell !== ''; }))) {
                        $validData[] = $row;
                    }
                }
                
                if (count($validData) < 3) {
                    $this->error('Excel文件数据不足');
                }
                
                // 解析所有产品数据
                $productModels = []; // 存储产品型号和数量
                
                for ($i = 3; $i < count($validData); $i++) {
                    $row = $validData[$i];
                    
                    // 只处理有产品名称和数量的行
                    if (!empty($row[1]) && !empty($row[4]) && is_numeric($row[4])) {
                        $fullProductName = trim($row[1]);
                        $color = !empty($row[2]) ? trim($row[2]) : '';
                        $spec = !empty($row[3]) ? trim($row[3]) : '';
                        $quantity = intval($row[4]);
                        
                        if ($quantity > 0) {
                            // 解析产品名称和型号编号
                            $parsedData = $this->parseProductName($fullProductName);
                            $productName = $parsedData['product_name'];
                            $modelCode = $parsedData['model_code'];
                            
                            // 处理规格中的特殊字符
                            $processedSpec = $this->processSpecification($spec, $productName);
                            
                            // 生成型号名称 - 只使用规格，不包含产品名和颜色
                            $modelName = $processedSpec;
                            
                            // 查找或创建产品型号
                            $modelId = $this->findOrCreateProductModel($productName, $color, $processedSpec, $modelName, $modelCode);
                            
                            if ($modelId) {
                                // 保持每个型号行的独立性，不合并相同型号
                                $productModels[] = [
                                    'model_id' => $modelId,
                                    'quantity' => $quantity
                                ];
                            }
                        }
                    }
                }
                
                if (empty($productModels)) {
                    $this->error('没有找到有效的产品数据');
                }
                
                // 获取表单数据
                $orderName = $this->request->post('order_name', '');
                $customerName = $this->request->post('customer_name', '青岛豪而美工贸有限公司');
                $customerPhone = $this->request->post('customer_phone', '');
                $deliveryTime = $this->request->post('delivery_time', '');
                $remark = $this->request->post('remark', '');
                
                // 转换交货时间
                error_log("导入订单 - 交货时间原始值: " . json_encode($deliveryTime));
                $deliveryTimestamp = null;
                if (!empty($deliveryTime)) {
                    $deliveryTimestamp = strtotime($deliveryTime);
                    error_log("导入订单 - 交货时间转换后: " . $deliveryTimestamp);
                }
                
                // 创建单个订单，包含所有产品
                $totalQuantity = array_sum(array_column($productModels, 'quantity'));
                
                $orderData = [
                    'order_no' => $this->generateOrderNo(),
                    'order_name' => $orderName,
                    'customer_name' => $customerName,
                    'customer_phone' => $customerPhone,
                    'total_quantity' => $totalQuantity,
                    'status' => 0,
                    'delivery_time' => $deliveryTimestamp,
                    'remark' => !empty($remark) ? $remark : 'Excel导入订单 - ' . date('Y-m-d H:i:s'),
                    'createtime' => time()
                ];
                
                // 保存订单到数据库
                Db::startTrans();
                try {
                    // 保存订单
                    $order = $this->model->create($orderData);
                    
                    // 保存订单型号
                    foreach ($productModels as $modelItem) {
                        \app\admin\model\scanwork\OrderModel::create([
                            'order_id' => $order->id,
                            'model_id' => $modelItem['model_id'],
                            'quantity' => $modelItem['quantity'],
                            'createtime' => time()
                        ]);
                    }
                    
                    Db::commit();
                    $this->success("成功导入订单，包含 " . count($productModels) . " 个产品型号，总数量 " . $totalQuantity . " 件");
                    
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error('导入失败：' . $e->getMessage());
                }
                
            } catch (Exception $e) {
                $this->error('文件读取失败：' . $e->getMessage());
            }
        }
        
        return $this->view->fetch();
    }
    
    /**
     * 解析产品名称，提取基础产品名和型号编号
     */
    private function parseProductName($fullProductName)
    {
        // 匹配格式：30013-7, 30013-10 等
        if (preg_match('/^(.+?)-(\d+)$/', $fullProductName, $matches)) {
            return [
                'product_name' => $matches[1], // 基础产品名，如 30013
                'model_code' => $matches[2]    // 型号编号，如 7, 10
            ];
        }
        
        // 如果没有匹配到格式，返回原名称作为产品名，空字符串作为型号编号
        return [
            'product_name' => $fullProductName,
            'model_code' => ''
        ];
    }
    
    /**
     * 处理规格中的特殊字符
     */
    private function processSpecification($spec, $productName = '')
    {
        if (empty($spec)) {
            return '';
        }
        
        // 总是优先查找数据库中该产品下已有的型号规格
        if (!empty($productName)) {
            $existingSpecs = $this->getExistingSpecifications($productName);
            if (!empty($existingSpecs)) {
                // 根据数据库中已有的规格来决定转换方向
                $convertedSpec = $this->convertSpecBasedOnExisting($spec, $existingSpecs);
                error_log("规格转换: {$spec} -> {$convertedSpec} (基于现有规格: " . implode(',', $existingSpecs) . ")");
                return $convertedSpec;
            }
        }
        
        // 只有在没有现有规格参考时才使用默认转换规则
        $convertedSpec = $this->convertSpecDefault($spec);
        error_log("规格转换: {$spec} -> {$convertedSpec} (使用默认规则)");
        return $convertedSpec;
    }
    
    /**
     * 获取指定产品下已有的型号规格
     */
    private function getExistingSpecifications($productName)
    {
        try {
            $product = \app\admin\model\scanwork\Product::where('name', $productName)->find();
            if (!$product) {
                return [];
            }
            
            $models = \app\admin\model\scanwork\ProductModel::where('product_id', $product->id)
                ->where('status', 1)
                ->select();
            
            $specs = [];
            foreach ($models as $model) {
                $modelName = $model->name;
                // 现在型号名称就是规格部分，直接添加
                $specs[] = $modelName;
            }
            
            return array_unique($specs);
        } catch (Exception $e) {
            error_log("获取现有规格失败：" . $e->getMessage());
            return [];
        }
    }
    
    /**
     * 根据现有规格决定转换方向
     */
    private function convertSpecBasedOnExisting($spec, $existingSpecs)
    {
        // 定义转换映射
        $conversionMappings = [
            '妃' => 'F',
            'F' => '妃',
            '踏' => 'T',
            't' => 'T',
            'T' => '踏'
        ];
        
        // 优先检查反向转换：如果Excel中是F/T，但数据库中是妃/踏
        foreach ($conversionMappings as $from => $to) {
            if (strpos($spec, $to) !== false) {
                // 检查反向转换后的规格是否在现有规格中存在
                $testConverted = str_replace($to, $from, $spec);
                if (in_array($testConverted, $existingSpecs)) {
                    return $testConverted; // 直接返回转换后的结果
                }
            }
        }
        
        // 如果没有找到反向转换，再检查正向转换
        foreach ($conversionMappings as $from => $to) {
            if (strpos($spec, $from) !== false) {
                // 检查转换后的规格是否在现有规格中存在
                $testConverted = str_replace($from, $to, $spec);
                if (in_array($testConverted, $existingSpecs)) {
                    return $testConverted;
                }
            }
        }
        
        // 如果都没有找到匹配，返回原规格
        return $spec;
    }
    
    /**
     * 默认转换规则（当没有现有规格参考时使用）
     */
    private function convertSpecDefault($spec)
    {
        // 默认转换规则：妃->F, 踏->T, t->T
        // 注意：这只是默认规则，实际应该优先使用convertSpecBasedOnExisting
        $specMappings = [
            '妃' => 'F',
            '踏' => 'T',
            't' => 'T'
        ];
        
        $processedSpec = $spec;
        foreach ($specMappings as $from => $to) {
            $processedSpec = str_replace($from, $to, $processedSpec);
        }
        
        return $processedSpec;
    }
    
    /**
     * 查找或创建产品和型号
     */
    private function findOrCreateProductModel($productName, $color, $spec, $modelName, $modelCode = '')
    {
        // 1. 先查找产品是否存在
        $product = \app\admin\model\scanwork\Product::where('name', $productName)->find();
        
        if (!$product) {
            // 创建产品
            $product = \app\admin\model\scanwork\Product::create([
                'name' => $productName,
                'status' => 1,
                'createtime' => time()
            ]);
        }
        
        // 2. 查找型号是否存在
        $model = \app\admin\model\scanwork\ProductModel::where('name', $modelName)
            ->where('product_id', $product->id)
            ->find();
            
        if (!$model) {
            // 创建型号
            $model = \app\admin\model\scanwork\ProductModel::create([
                'product_id' => $product->id,
                'name' => $modelName,
                'model_code' => $modelCode,
                'status' => 1,
                'createtime' => time()
            ]);
            
            // 为新创建的型号设置默认工价
            $this->createDefaultProcessPrices($model->id);
        }
        
        return $model->id;
    }
    
    /**
     * 为新创建的型号设置默认工价
     */
    private function createDefaultProcessPrices($modelId)
    {
        try {
            // 获取所有工序
            $processes = \app\admin\model\scanwork\Process::where('status', 1)->select();
            
            foreach ($processes as $process) {
                // 检查是否已存在该型号的工序工价
                $existingPrice = \app\admin\model\scanwork\ProcessPrice::where('model_id', $modelId)
                    ->where('process_id', $process->id)
                    ->find();
                
                if (!$existingPrice) {
                    // 创建默认工价记录
                    \app\admin\model\scanwork\ProcessPrice::create([
                        'model_id' => $modelId,
                        'process_id' => $process->id,
                        'price' => 1.00, // 默认计件工价为1
                        'time_price' => 1.00, // 默认计时工价为1
                        'status' => 1,
                        'createtime' => time()
                    ]);
                }
            }
        } catch (Exception $e) {
            // 记录错误但不影响主流程
            error_log("创建默认工价失败：" . $e->getMessage());
        }
    }

    /**
     * 下载Excel模板
     */
    public function downloadTemplate()
    {
        try {
            $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
            $sheet = $spreadsheet->getActiveSheet();
            
            // 设置标题
            $sheet->setCellValue('A1', '2025年8.14号青岛豪而美工贸有限公司生产计划');
            $sheet->mergeCells('A1:J1');
            
            // 设置表头
            $sheet->setCellValue('A2', '序号');
            $sheet->setCellValue('B2', '产品名称');
            $sheet->setCellValue('C2', '颜色');
            $sheet->setCellValue('D2', '规格');
            $sheet->setCellValue('E2', '数量');
            $sheet->setCellValue('F2', '出货日期');
            $sheet->setCellValue('G2', '卜料');
            $sheet->setCellValue('H2', '木1');
            $sheet->setCellValue('I2', '详细');
            $sheet->setCellValue('J2', '扪皮');
            
            // 设置示例数据（根据实际Excel文件格式）
            $exampleData = [
                [1, '30012-7', '白色', '3+妃', 45, '', '', '', '', ''],
                [2, '30012-7', '白色', '3+妃', 15, '', '', '', '', ''],
                ['', '30013', '黑色', '3+踏', 36, '', '', '', '', ''],
                [3, '909-1', '浅灰色', '3人', 40, '', '', '', '✔', ''],
                [4, '30011-1', '白色', '3人', 87, '', '', '', '', ''],
                ['', '', '', '踏', 50, '', '', '', '', ''],
                [5, '608-5', '白色', '2人', 30, '', '', '', '', ''],
                ['', '616', '白色', '3人', 30, '', '', '', '', ''],
                ['', '', '', '踏', 20, '', '', '', '', ''],
                ['', '616-1', '黑色', '3人', 30, '', '', '', '', ''],
                ['', '', '', '踏', 20, '', '', '', '', ''],
                ['', '907-1', '灰色', '1人', 20, '', '', '', '', '']
            ];
            
            $row = 3;
            foreach ($exampleData as $data) {
                $col = 'A';
                foreach ($data as $value) {
                    $sheet->setCellValue($col . $row, $value);
                    $col++;
                }
                $row++;
            }
            
            // 设置列宽
            $sheet->getColumnDimension('A')->setWidth(8);
            $sheet->getColumnDimension('B')->setWidth(15);
            $sheet->getColumnDimension('C')->setWidth(10);
            $sheet->getColumnDimension('D')->setWidth(10);
            $sheet->getColumnDimension('E')->setWidth(10);
            $sheet->getColumnDimension('F')->setWidth(12);
            $sheet->getColumnDimension('G')->setWidth(8);
            $sheet->getColumnDimension('H')->setWidth(8);
            $sheet->getColumnDimension('I')->setWidth(8);
            $sheet->getColumnDimension('J')->setWidth(8);
            
            // 设置样式
            $sheet->getStyle('A1:J1')->getFont()->setBold(true)->setSize(14);
            $sheet->getStyle('A2:J2')->getFont()->setBold(true);
            $sheet->getStyle('A2:J2')->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
            
            // 设置边框
            $sheet->getStyle('A2:J' . ($row-1))->getBorders()->getAllBorders()->setBorderStyle(\PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN);
            
            // 输出文件
            $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
            $filename = '订单导入模板_' . date('YmdHis') . '.xlsx';
            
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            header('Content-Disposition: attachment;filename="' . $filename . '"');
            header('Cache-Control: max-age=0');
            
            $writer->save('php://output');
            exit;
            
        } catch (Exception $e) {
            $this->error('模板生成失败：' . $e->getMessage());
        }
    }

    /**
     * 计算订单物料需求及成本
     */
    private function calculateMaterialsWithCost($orderId)
    {
        $order = \app\admin\model\scanwork\Order::with(['orderModels.model'])->find($orderId);
        if (!$order) {
            \think\Log::info("物料计算 - 订单不存在，ID: " . $orderId);
            return [];
        }
        
        \think\Log::info("物料计算 - 订单型号数量: " . count($order->orderModels));
        
        $materialNeeds = [];
        
        foreach ($order->orderModels as $orderModel) {
            $quantity = $orderModel->quantity;
            $modelId = $orderModel->model_id;
            
            \think\Log::info("物料计算 - 处理型号ID: " . $modelId . ", 数量: " . $quantity);
            
            // 获取该型号所有工序的物料需求
            $processMaterials = \app\admin\model\scanwork\ProcessMaterial::where('model_id', $modelId)
                ->with(['material'])
                ->select();
            
            \think\Log::info("物料计算 - 型号 " . $modelId . " 的工序物料数量: " . count($processMaterials));
            
            foreach ($processMaterials as $pm) {
                // 计算需求量（含损耗）
                $needQty = $quantity * $pm->quantity * (1 + $pm->loss_rate / 100);
                
                if (!isset($materialNeeds[$pm->material_id])) {
                    // 获取最优供应商价格
                    $bestPrice = $pm->material->current_price;
                    $bestSupplierId = $pm->material->default_supplier_id;
                    
                    // 单独查询最优供应商
                    $bestSupplier = \app\admin\model\scanwork\MaterialSupplier::where('material_id', $pm->material_id)
                        ->where('status', 1)
                        ->where('is_preferred', 1)
                        ->order('price', 'asc')
                        ->find();
                    
                    if ($bestSupplier) {
                        $bestPrice = $bestSupplier->price;
                        $bestSupplierId = $bestSupplier->supplier_id;
                    }
                    
                    $materialNeeds[$pm->material_id] = [
                        'material' => $pm->material,
                        'quantity' => 0,
                        'price' => $bestPrice,
                        'supplier_id' => $bestSupplierId,
                        'amount' => 0,
                        'loss_rate' => $pm->loss_rate
                    ];
                }
                
                $materialNeeds[$pm->material_id]['quantity'] += $needQty;
                $materialNeeds[$pm->material_id]['amount'] = 
                    $materialNeeds[$pm->material_id]['quantity'] * 
                    $materialNeeds[$pm->material_id]['price'];
            }
        }
        
        // 保存到订单物料需求表
        foreach ($materialNeeds as $materialId => $data) {
            \app\admin\model\scanwork\OrderMaterial::create([
                'order_id' => $orderId,
                'material_id' => $materialId,
                'required_quantity' => $data['quantity'],
                'estimated_price' => $data['price'],
                'estimated_amount' => $data['amount'],
                'supplier_id' => $data['supplier_id'],
                'loss_rate' => $data['loss_rate'],
                'purchase_status' => 0,
                'stock_status' => 0
            ]);
        }
        
        return $materialNeeds;
    }

    /**
     * 查看订单物料清单
     */
    public function materialList($ids = null)
    {
        $order = \app\admin\model\scanwork\Order::find($ids);
        if (!$order) {
            $this->error(__('No Results were found'));
        }
        
        // 调试信息：检查delivery_time字段
        \think\Log::info("物料清单 - 订单ID: " . $ids);
        \think\Log::info("物料清单 - delivery_time值: " . json_encode($order->delivery_time));
        \think\Log::info("物料清单 - delivery_time类型: " . gettype($order->delivery_time));
        
        // 确保delivery_time是整数
        if (!empty($order->delivery_time) && is_string($order->delivery_time)) {
            $order->delivery_time = (int)$order->delivery_time;
            \think\Log::info("物料清单 - 转换delivery_time为整数: " . $order->delivery_time);
        }
        
        // 每次访问都重新计算物料需求
        \think\Log::info("物料清单 - 开始自动计算物料需求，订单ID: " . $ids);
        
        // 先删除现有物料记录
        \app\admin\model\scanwork\OrderMaterial::where('order_id', $ids)->delete();
        
        // 重新计算物料需求
        $result = $this->calculateMaterialsWithCost($ids);
        \think\Log::info("物料清单 - 计算完成，结果数量: " . count($result));
        
        // 获取重新计算后的物料需求
        $orderMaterials = \app\admin\model\scanwork\OrderMaterial::with(['material', 'supplier'])
            ->where('order_id', $ids)
            ->select();
        \think\Log::info("物料清单 - 最终物料数量: " . count($orderMaterials));
        
        // 重新获取最新的物料库存信息
        foreach ($orderMaterials as $om) {
            if ($om->material_id) {
                $latestMaterial = \app\admin\model\scanwork\Material::find($om->material_id);
                if ($latestMaterial) {
                    \think\Log::info("物料清单 - 更新库存: 物料ID={$om->material_id}, 名称={$latestMaterial->name}, 库存={$latestMaterial->stock}");
                    $om->material = $latestMaterial;
                }
            }
        }
        
        // 统计总成本和缺料情况
        $totalAmount = 0;
        $shortageCount = 0;
        foreach ($orderMaterials as $om) {
            $totalAmount += $om->estimated_amount;
            // 检查是否缺料
            if ($om->material && $om->required_quantity > $om->material->stock) {
                $shortageCount++;
            }
        }
        
        $this->view->assign('order', $order);
        $this->view->assign('orderMaterials', $orderMaterials);
        $this->view->assign('totalAmount', $totalAmount);
        $this->view->assign('shortageCount', $shortageCount);
        
        return $this->view->fetch();
    }

    /**
     * 更新物料备料状态
     */
    public function updateMaterialStatus()
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        
        $id = $this->request->post('id');
        $field = $this->request->post('field');
        $value = $this->request->post('value');
        
        if (!$id || !$field) {
            $this->error(__('Parameter %s can not be empty', 'id/field'));
        }
        
        $orderMaterial = \app\admin\model\scanwork\OrderMaterial::get($id);
        if (!$orderMaterial) {
            $this->error(__('No Results were found'));
        }
        
        try {
            $orderMaterial->save([$field => $value]);
            $this->success('更新成功');
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }
} 